<script lang="ts" setup>
import { ref ,watch,onMounted } from 'vue'
import axios from 'axios'
import {ElMessage, TabsPaneContext} from 'element-plus'
import CarList from "@/components/carList.vue";
import { useRouter } from 'vue-router'


const router = useRouter()

const activeName = ref('first')
const typePage = ref([])

const findType = async () => {
  try {
    const resp = await axios.get('/carType/findAll')
    typePage.value = resp.data;
  } catch (error) {
    console.error('Error fetching car types:', error);
  }
}
const goToHome = async () => {
  activeName.value = 'first'; // 切换到“按类别查看”标签页
};


const cars = ref({});
const param = ref({
  pageNum: 1,
  pageSize: 5,

});
const carAll = async () => {
  const resp = await axios.post('/car/all', param.value);
  cars.value = resp.data;
};
const handleCurrentPage = (val) => {
  param.value.pageNum = val;
  carAll();
};

const handleTypeCurrentPage = (val) => {
  param.value.pageNum = val;
  findByType();
};

const handleSalesCurrentPage = (val) => {
  param.value.pageNum = val;
  findByPrice();
}


const handleTabChange = (tab) => {
  const typeId = tab.props.name;
  param.value.pageNum = 1;

  // 这里重置 priceRange
  param.value.priceRange = null; // 或者根据你的需求设置为 '不限'

  if (typeId === "hotSelling") {
    param.value.typeId = null; // 清除类型ID以便获取热销车
    carAll();
  } else {
    param.value.typeId = typeId; // 设置当前类型ID
    findByType();
  }
};

const carTypes = ref([]);
const findByType = async () => {
  param.value.priceRange = null;
  try {
    const resp = await axios.post('/car/findByType', param.value);
    carTypes.value = resp.data;
  } catch (error) {
    console.error('Error fetching cars by type:', error);
  }
};


const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
}

// 监视 activeName 的变化
watch(activeName, (newValue) => {
  if (newValue === 'first') {
    findType();
  }
  if (newValue === 'second') {
    findByPrice();
  }
  if (newValue === 'compare') {
    getCompare();
  }

});

const handleTabClick = (tab) => {
  const priceRange = tab.props.name;
  param.value.pageNum = 1; // 重置当前页面
  param.value.priceRange = priceRange; // 设置当前选择的售价范围
  findByPrice(); // 调用按售价过滤的函数
};

const carPrices = ref([]);
const findByPrice = async () => {
  // 处理价格范围
  const priceRanges = {
    '不限': [null, null],
    '30万以下': [null, 300000],
    '30万-60万': [300000, 600000],
    '60万-100万': [600000, 1000000],
    '100万-200万': [1000000, 2000000],
    '200万以上': [2000000, null],
  };

  const [minPrice, maxPrice] = priceRanges[param.value.priceRange] || [null, null];

  try {
    const resp = await axios.post('/car/findByPrice', {
      ...param.value,
      minPrice,
      maxPrice,
    });
    carPrices.value = resp.data;
  } catch (error) {
    console.error('Error fetching cars by price:', error);
  }
};

const compare = ref([])
const getCompare=async ()=>{
  const resp = await axios.get('/car/getCompare')
  compare.value=resp.data
}

const removeCar = async (productId) => {
  try {
    await axios.post('/car/removeCompare', { productId });
    await getCompare(); // 重新获取对比列表
  } catch (error) {
    console.error('Error removing car from comparison:', error);
  }
};
const calculateMonthlyPayment = (price) => {
  const interestRate = 0.05;
  const months = 120;
  const monthlyRate = interestRate / 12;
  const monthlyPayment = (price * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -months));
  return monthlyPayment > 0 ? monthlyPayment.toFixed(2) : '0.00';
};

const isAddingFavorite = ref(false); // 用于标记是否正在添加
const addFavorite = async (productId) => {
  isAddingFavorite.value = true; // 设置为正在添加状态
  try {
    await axios.post(`/favorites/add/${productId}`);
    ElMessage.success('已添加到收藏夹');
    await getCompare();
  } catch (error) {
    // 提取错误信息并显示
    const message = error.response?.data || '添加失败，请重试';
    ElMessage.info(message);
  } finally {
    // 暂停3秒后重置状态
    setTimeout(() => {
      isAddingFavorite.value = false;
    }, 3000);
  }
}



onMounted(() => {
  findType();
  findByPrice();
  carAll();
  getCompare();

})
</script>

<template>
  <el-row justify="center" style="padding: 0 20px;">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="width: 100%;">
      <el-tab-pane label="按类别查看" name="first">
        <el-tabs  @tab-click="handleTabChange" name="hotSelling">
          <el-tab-pane label="不限">
            <car-list :car-list="cars.records"
                      :current-page="param.pageNum"
                      :page-size="param.pageSize"
                      :total-items="cars.total"
                      @change-page="handleCurrentPage">
            </car-list>
          </el-tab-pane>
          <el-tab-pane v-for="type in typePage" :key="type.categoryId" :label="type.categoryName" :name="String(type.categoryId)">
            <car-list :car-list="carTypes.records"
                      :current-page="param.pageNum"
                      :page-size="param.pageSize"
                      :total-items="carTypes.total"
                      @change-page="handleTypeCurrentPage">
            </car-list>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
      <el-tab-pane label="按条件筛选" name="second">
            <el-form>
              <el-form-item label="售价：" label-style="font-size: 18px;">
                <div style="display: flex; align-items: center;">
                  <el-tabs @tab-click="handleTabClick" name="salePrice">
                    <el-tab-pane label="不限" name="不限">
                      <car-list :car-list="carPrices.records"
                                :current-page="param.pageNum"
                                :page-size="param.pageSize"
                                :total-items="carPrices.total"
                                @change-page="handleSalesCurrentPage">
                      </car-list>
                    </el-tab-pane>
                    <el-tab-pane label="30万以下" name="30万以下">
                      <car-list :car-list="carPrices.records"
                                :current-page="param.pageNum"
                                :page-size="param.pageSize"
                                :total-items="carPrices.total"
                                @change-page="handleSalesCurrentPage">
                      </car-list>
                    </el-tab-pane>
                    <el-tab-pane label="30万-60万" name="30万-60万">
                      <car-list :car-list="carPrices.records"
                                :current-page="param.pageNum"
                                :page-size="param.pageSize"
                                :total-items="carPrices.total"
                                @change-page="handleSalesCurrentPage">
                      </car-list>
                    </el-tab-pane>
                    <el-tab-pane label="60万-100万" name="60万-100万">
                      <car-list :car-list="carPrices.records"
                                :current-page="param.pageNum"
                                :page-size="param.pageSize"
                                :total-items="carPrices.total"
                                @change-page="handleSalesCurrentPage">
                      </car-list>
                    </el-tab-pane>
                    <el-tab-pane label="100万-200万" name="100万-200万">
                      <car-list :car-list="carPrices.records"
                                :current-page="param.pageNum"
                                :page-size="param.pageSize"
                                :total-items="carPrices.total"
                                @change-page="handleSalesCurrentPage">
                      </car-list>
                    </el-tab-pane>
                    <el-tab-pane label="200万以上" name="200万以上">
                      <car-list :car-list="carPrices.records"
                                :current-page="param.pageNum"
                                :page-size="param.pageSize"
                                :total-items="carPrices.total"
                                @change-page="handleSalesCurrentPage">
                      </car-list>
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
      <el-tab-pane label="车辆对比" name="compare">
        <el-row :gutter="20" justify="center">
          <template v-if="compare.length === 0">
            <el-col v-for="n in 3" :key="n" :span="6">
              <div class="empty-car-card" @click="goToHome">
                <svg class="add-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <line x1="12" y1="5" x2="12" y2="19"></line>
                  <line x1="5" y1="12" x2="19" y2="12"></line>
                </svg>
                <p> 暂无车辆对比</p>
              </div>
            </el-col>
          </template>
          <template v-else>
            <el-col v-for="car in compare" :key="car.productId" :span="6">
              <div class="car-card">
                <el-button class="add-btn" @click="addFavorite(car.productId)" :disabled="isAddingFavorite">+</el-button>
                <button class="delete-btn" @click="removeCar(car.productId)">-</button>
                <img :src="$urlImage + car.imgs" alt="车图" style="width: 100%; height: 200px;" />
                <div class="car-info">
                  <h3>{{ car.name }}</h3>
                  <p><strong>编号:</strong> {{ car.productId }}</p>
                  <p><strong>月付:</strong> ¥{{ calculateMonthlyPayment(car.price) }} 起</p>
                  <p><strong>库存:</strong> {{ car.stock }} 辆</p>
                  <p><strong>油耗:</strong> {{ car.fuelConsumption }} (L/每100公里)</p>
                  <p><strong>最高速度:</strong> {{ car.maxSpeed }} (公里/小时)</p>
                  <p><strong>加速度:</strong> {{ car.acceleration }}
                    <el-popover
                        placement="top-start"
                        :width="180"
                        trigger="hover"
                        content="0-100公里/小时（秒）">
                      <template #reference>
                    <span style="cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                        <path d="M12 0a12 12 0 1 0 12 12A12.013 12.013 0 0 0 12 0zm0 22a10 10 0 1 1 10-10 10.012 10.012 0 0 1-10 10zm1-15h-2v2h2zm0 4h-2v6h2z"/>
                      </svg>
                    </span>
                      </template>
                    </el-popover>
                  </p>
                  <p><strong>能源:</strong> {{ car.energy }}</p>
                  <p><strong>座位数:</strong> {{ car.seatCount }}</p>
                </div>
              </div>
            </el-col>
          </template>
        </el-row>
        <div style="text-align: center; margin-top: 20px;">
          <p>注：您可以选择最多3款车辆进行对比，便于做出更好的购买决策。</p>
          <p>点击“+”按钮可将该车辆添加到我的心愿订单中，点击“-”按钮可将该车辆从对比列表中移除。</p>
        </div>
      </el-tab-pane>

    </el-tabs>
  </el-row>

  <el-backtop :right="100" :bottom="100" />

</template>

<style scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

/* 控制左右间距 */
.el-tabs {
  max-width: 1200px; /* 你可以根据需要调整这个值 */
  margin: 0 auto; /* 居中对齐 */
}
.car-card {
  position: relative; /* 使卡片相对定位 */
  border: 1px solid #070505;
  border-radius: 5px;
  padding: 10px;
  text-align: left;
}

.delete-btn {
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离上边10px */
  right: 10px; /* 距离右边10px */
  background-color: red; /* 按钮背景颜色 */
  color: white; /* 按钮文字颜色 */
  border: none; /* 无边框 */
  border-radius: 50%; /* 圆形按钮 */
  width: 30px; /* 按钮宽度 */
  height: 30px; /* 按钮高度 */
  font-size: 20px; /* 字体大小 */
  cursor: pointer; /* 鼠标样式 */
}
.add-btn{
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离上边10px */
  left: 10px; /* 距离右边10px */
  background-color: blue; /* 按钮背景颜色 */
  color: white; /* 按钮文字颜色 */
  border: none; /* 无边框 */
  border-radius: 50%; /* 圆形按钮 */
  width: 30px; /* 按钮宽度 */
  height: 30px; /* 按钮高度 */
  font-size: 20px; /* 字体大小 */
  cursor: pointer; /* 鼠标样式 */
}

.delete-btn:hover {
  background-color: darkred; /* 悬停效果 */
}

.empty-car-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #ccc; /* 可视化的框线 */
  height: 200px; /* 高度根据需要调整 */
  border-radius: 5px;
  text-align: center;
  padding: 20px;
}

.add-icon {
  width: 50px; /* 加号图标的宽度 */
  height: 50px; /* 加号图标的高度 */
  margin-bottom: 10px; /* 图标和文本的间距 */
}

</style>
